package com.study.cloud.config;

import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * log过滤
 *
 * @author Teler
 */
public class LogFilter implements Filter {


    @Override
    public void init(FilterConfig config) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {

        //为了在post的时候能继续传递
        LogHttpServletRequestWrapper request = new LogHttpServletRequestWrapper((HttpServletRequest) servletRequest);
        MyResponseWrapper response = new MyResponseWrapper((HttpServletResponse) servletResponse);

        StaticLog.info("=====================LogFilter前置start=====================>");

        //封装log实体类
        Map<String, Object> parameterMap=new LinkedHashMap<>();
        if("GET".equals(request.getMethod())){
            parameterMap= JSONUtil.parseObj(ServletUtil.getParams(request));
        }else{
            parameterMap= JSONUtil.parseObj(request.getBody());
        }
        StaticLog.info("请求来源： =》{}", request.getRemoteAddr());
        StaticLog.info("请求URI：{}", request.getRequestURI());
        StaticLog.info("请求方式：{}", request.getMethod());
        StaticLog.info("请求参数：{}", parameterMap);
        StaticLog.info("=====================LogFilter前置  end=====================>");
        //消耗时间
        long start = System.currentTimeMillis();

        // 执行主体方法start==================================================================
        chain.doFilter(request, response);
        // 执行主体方法  end==================================================================

        //耗时
        long time = System.currentTimeMillis() - start;
        StaticLog.info("=====================LogFilter后置start=====================>");
        byte[] content=response.getContent();
        String resultParams=new String();
        if (content.length > 0) {
            resultParams= new String(content, "UTF-8");
        }
        StaticLog.info("返回值：{}", resultParams);
        StaticLog.info("耗时（毫秒）：", time);
        //返回消息 否则前台收不到消息
        servletResponse.getOutputStream().write(resultParams.getBytes());
        StaticLog.info("=====================LogFilter后置  end=====================>");
    }

    @Override
    public void destroy() {
    }
}

